"""
销量预测接口
"""
# sfb
import json
from fastapi import APIRouter
from pydantic import BaseModel

# zjb

from core import scatterSql, sectionLevelSql, fieldSelect, generalSelect
from core.utils import SelfJSONResponse

statistics = APIRouter(tags=["统计分析"], prefix="/statisticsAction")


@statistics.get("/getScatterField", summary="获取离散型数据统计")
async def getScatterField(fieldName, order):
    sql = scatterSql(fieldName=fieldName, order=order)
    results = fieldSelect(sql, fieldName=fieldName)
    return SelfJSONResponse(code=200,
                            data=results,
                            msg="查询成功！")


class QueryData(BaseModel):
    fieldName: str
    levelName: list
    levelNum: list

    def getJson(self):
        return {
            'fieldName': self.fieldName,
            'levelName': self.levelName,
            'levelNum': self.levelNum,
        }


@statistics.post("/getSectionField", summary="获取区间型数据统计")
async def getSectionField(queryData: QueryData):
    sql = sectionLevelSql(fieldName=queryData.fieldName, levelName=queryData.levelName, levelNum=queryData.levelNum)
    results = fieldSelect(sql, fieldName=queryData.fieldName)
    return SelfJSONResponse(code=200,
                            data=results,
                            msg="查询成功！")


@statistics.get("/getFinalManuFacturePrice", summary="获取落地价和出厂价数据统计")
async def getFinalManuFacturePrice():
    sql = "select series_id, manufacture, final_price, manufacture_price " \
          "from car_infomation " \
          "where final_price <> 0 " \
          "GROUP BY series_id " \
          "order by manufacture"
    rows = generalSelect(sql)
    result = {
        "series_id": [],
        "manufacture": [],
        "final_price": [],
        "manufacture_price": []
    }
    for row in rows:
        result["series_id"].append(row[0])
        result["manufacture"].append(row[1])
        result["final_price"].append(row[2])
        result["manufacture_price"].append(row[3])
    return SelfJSONResponse(code=200,
                            data=result,
                            msg="查询成功！")


@statistics.get("/getFuelConsumption", summary="获取落地价和出厂价数据统计")
async def getFuelConsumption():
    sql = "select manufacture, fuel_consumption_MIIT " \
          "from car_infomation " \
          "where fuel_consumption_MIIT <> 0 " \
          "GROUP BY manufacture " \
          "order by manufacture"
    rows = generalSelect(sql)
    return SelfJSONResponse(code=200,
                            data=rows,
                            msg="查询成功！")


@statistics.get("/getCarInfomation", summary="获取汽车数据统计")
def getCarInfomation(pageNum: int, pageSize: int, finalPrice: float = None, manufacture: str = None, ):
    # queryData
    start = (pageNum - 1) * pageSize
    end = pageSize
    sql = "select * from car_infomation "
    sql = finalPriceManufactureSelect(sql, finalPrice, manufacture)
    sql += " limit {}, {};".format(str(start), str(end))
    rows = generalSelect(sql)

    countSql = "select count(*) from car_infomation "
    countSql = finalPriceManufactureSelect(countSql, finalPrice, manufacture)
    count = generalSelect(countSql)

    result = {
        "rows": rows,
        "total": count[0][0]
    }

    return SelfJSONResponse(code=200,
                            data=result,
                            msg="查询成功！")


def finalPriceManufactureSelect(sql, finalPrice, manufacture):
    if finalPrice:
        sql += "where final_price <= {}".format(finalPrice)
    elif manufacture:
        sql += "where manufacture like '%{}%'".format(manufacture)
    elif finalPrice and manufacture:
        sql += "where final_price <= {} and manufacture like '%{}%'".format(finalPrice, manufacture)

    return sql